# ====================================
# Company: Zonge International, INC.
# Developer: Wanjie Feng
# Date: 11/11/2023
# Time: 6:02 PM
# Filename: Send_Command.py
# IDE: PyCharm
# =====================================
import os
from Read_cvs import Read_cvs
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from os.path import dirname, join


def SendCMD(TXFrq, TXDuty, CycleNO, TXLoc, TXMode, RXLoc, Filter, Gain):
    '''
        发送命令到主机，返回系统信息，数据
        :param TXFrq:
        :param TXDuty:
        :param CycleNO:
        :param StackNO:
        :param TXLoc:
        :param TXMode:
        :param RXLoc:
        :param Filter
        :param Gain
        :return: SysInfo, Data
    '''
    SysInfo = {}
    SysInfo['SysBatV'] = 12.5                       # 仪器电池电压
    SysInfo['SysTemp'] = 30                         # 仪器温度
    SysInfo['RXSR'] = 1000                          # 采样频率
    SysInfo['Gain'] = 0                             # 增益关
    SysInfo['Filter'] = 1                           # 50Hz陷波开
    SysInfo['CRES'] = 0.8                           # 接地电阻

    ###这里采用读取一个cvs文件的方式模拟仪器返回的一个数据
    CurrentDir = os.path.dirname(os.path.abspath(__file__))  # current direcotry
    os.chdir(CurrentDir)
    #filepath = CurrentDir + '\\out_A1_B12_M2_N3_20231029T232708.cvs'
    filepath = join(dirname(__file__), "out_A1_B12_M2_N3_20231029T232708.cvs")
    Data = Read_cvs(filepath)
    #实际数据采集中，我们只需要保存发射电流和接收电压的值。现在仪器采集的数据和我们发送给仪器的命令是不同的，因此这里采用合成的方式形成采集的数据
    #上述的数据读取部分可供参考
    #!!!!!以下为数据模拟过程，不需要编写到手部里
    NFFT = SysInfo['RXSR'] *  CycleNO/TXFrq             # number of points
    SR = SysInfo['RXSR']                                # sampling rate
    A = 1                                               # mag
    Phs = 0                                             # phase
    SF = TXFrq                                          # square wave frequency
    Delta_T = 1 / SR                                    # sampling interval
    t = np.arange(0, NFFT, 1) * Delta_T                 # Time vector
    TX_I = A * signal.square(2*np.pi * SF * t + Phs) + \
        A * signal.square(2*np.pi * SF * t + Phs + np.pi/2)                       # TX_I wave
    RX_V = A * signal.square(2*np.pi * SF * t + Phs) +\
        A * signal.square(2*np.pi * SF * t + Phs + np.pi/2)    # RX_V wave
    Decay = 2*np.exp(-16*np.pi * SF * np.arange(0,SR/TXFrq/4)*Delta_T)
    temp = np.zeros((int(SR/TXFrq),))
    temp[int(SR/TXFrq/4):int(SR/TXFrq/2)] = Decay
    temp[int(3*SR/TXFrq/4):int(SR/TXFrq)] = -Decay
    #add Decay to RX_V to simulate a response
    for I in range(CycleNO):
        stp = int(I*SR/TXFrq)
        endp = int((I+1)*SR/TXFrq)
        RX_V[stp:endp] = RX_V[stp:endp] + temp
    Data = np.vstack((TX_I,RX_V)).T
    # print("+++++++++++++++++++++++++++++++++++++++++++ sendCommand +++++++++++++++++++++++++++++++++++++++++++++++++++")
    return SysInfo, Data